package com.e3.basdoc.currency.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.currency.dao.CurrencyDAO;
import com.e3.basdoc.currency.entity.CurrencyEntity;
import com.e3.basdoc.currency.model.CurrencyModel;
import com.e3.basdoc.currency.model.CurrencyQC;
import com.e3.basdoc.currency.service.CurrencyCacheManager;
import com.e3.basdoc.currency.service.CurrencyQueryService;
import com.e3.core.base.DAOHelper;
import com.e3.core.base.ServiceException;
import com.e3.core.base.SuperQueryService;

public class CurrencyQueryServiceImpl extends SuperQueryService implements CurrencyQueryService{
	
	private CurrencyDAO currencyDAO;
	
	private CurrencyDAO getCurrencyDAO(){
		if(currencyDAO == null){
			currencyDAO = DAOHelper.createDAOInstance(CurrencyDAO.class);
		}
		return currencyDAO;
	}

	public List<CurrencyModel> getCurrencyByCondition(CurrencyQC qc) throws ServiceException {
		
		List<Long> ids = getCurrencyDAO().getCurrencyIdsByCondition(qc);
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<CurrencyModel> models = new ArrayList<CurrencyModel>(ids.size());
		for (Long id : ids) {
			CurrencyModel model = getCurrencyById(id);
			models.add(model);
		}
		return models;
	}
	/**
	 * the method is used to load data into cache.
	 */
	public List<CurrencyModel> getAllCurrencys() throws ServiceException {
		List<CurrencyEntity> entities = getCurrencyDAO().getAllCurrencys();
		if(entities==null||entities.isEmpty()){
			return null;
		}
		List<CurrencyModel> models = new ArrayList<CurrencyModel>(entities.size());
		for (CurrencyEntity currencyEntity : entities) {
			models.add(currencyEntityToModel(currencyEntity));
		}
		return models;
	}

	public CurrencyModel getCurrencyById(long id) throws ServiceException {
		CurrencyModel model = CurrencyCacheManager.INSTANCE.get(id);
		if(model==null){
			CurrencyEntity entity = getCurrencyDAO().getById(CurrencyEntity.class, id);
			model = currencyEntityToModel(entity);
			if(model != null){
				CurrencyCacheManager.INSTANCE.put(model);
			}
		}
		
		return model;
	}

	public List<CurrencyModel> getCurrencyByIds(List<Long> ids)	throws ServiceException {
		if(ids == null||ids.isEmpty()){
			return null;
		}
		
		List<CurrencyModel> models = new ArrayList<CurrencyModel>(ids.size());
		for (Long id : ids) {
			CurrencyModel model = getCurrencyById(id);
			models.add(model);
		}
		
		return models;
	}

	private CurrencyModel currencyEntityToModel(CurrencyEntity entity){
		
		if(entity == null){
			return null;
		}
		
		CurrencyModel model = new CurrencyModel();
		model = entityToModel(model, entity);
		
		model.setCode(entity.getCode());
		model.setName(entity.getName());
		model.setSign(entity.getSign());
		
		return model;
	}
}
